package me.leiusual.sharing.ui.store.adapter

import android.view.View
import androidx.core.content.res.ResourcesCompat
import androidx.recyclerview.widget.RecyclerView
import kotlinx.android.extensions.LayoutContainer
import kotlinx.android.synthetic.main.view_holder_store_area.*
import me.leiusual.sharing.R
import me.leiusual.sharing.api.model.storeproductquery.Product
import me.leiusual.sharing.util.extension.setImageUrl
import me.leiusual.sharing.util.extension.spToPx
import me.leiusual.sharing.util.extension.toSpanned
import q.rorbin.badgeview.Badge
import q.rorbin.badgeview.QBadgeView

/**
 * author: leiusual
 * create on: 2019-07-26
 * description:
 */
class StoreAreaViewHolder(
    override val containerView: View,
    private val clickListener: (Product) -> Unit
) : RecyclerView.ViewHolder(containerView), LayoutContainer, View.OnClickListener {

  private lateinit var product: Product
  private val badge: Badge

  init {
    containerView.setOnClickListener(this)
    val color = ResourcesCompat.getColor(containerView.resources, R.color.colorPrimary, null)
    badge = QBadgeView(image_view.context).bindTarget(image_view).setBadgeBackgroundColor(color)
  }

  fun bind(product: Product) {
    this.product = product

    image_view.setImageUrl(product.productImage)
    badge.badgeText = product.storeAreaNames

    // 价格
    val size = 8f.spToPx(containerView.context)

    val builder = StringBuilder()
    builder.append("""<font color="red">""")
    builder.append("""<size_$size>￥</size_$size>""")
    builder.append(product.sellingPrice)
    builder.append("""</font>""")
    if (product.salePrice.toDoubleOrNull() ?: 0.0 > 0 && product.sellingPrice != product.salePrice) {
      builder.append("""  <del><size_$size>￥</size_$size>${product.salePrice}</del>""")
    }
    text_view_price.text = builder.toString().toSpanned()

    // 积分
    builder.clear()
    val pointCoinString = product.priceVos.firstOrNull()?.pointCoinString
    if (!pointCoinString.isNullOrBlank()) {
      builder.append("""<font color="red">""")
      builder.append("""<size_$size>分</size_$size>$pointCoinString""")
      builder.append("""</font>""")
    }
    text_view_point_coin.text = builder.toString().toSpanned()

    text_view_product_name.text = product.productName

    text_view_store_name.text = product.storeName

    text_view_total.text = "总销量${product.soldTotal}笔"
  }

  override fun onClick(v: View) {
    clickListener(product)
  }
}